// application/json
const my = function(req,cb){
	if(req.body){
		cb();
	}else{
		req.body = "";
		req.on("data",function(thunk){
			req.body+=thunk;
		});
		req.on("end",function(){
			// 数据接收完毕
			cb();
		})
	}

}
module.exports = {
	cors(){
		return function(req,res,next){
			res.set("Access-Control-Allow-Origin","*");
			res.set("Access-Control-Allow-Methods","*");
			res.set("Access-Control-Allow-Headers","*");
			next();
		}
	},
	json(){
		return function(req,res,next){
			if(req.method==="POST"){
				my(req,function(){
					if(req.headers["content-type"]==="application/json"){
						req.body = JSON.parse(req.body);
					}
					next();
				});
			}else{
				next();
			}
		}
	},
	urlencoded(){
		return function(req,res,next){
			if(req.method==="POST"){
				my(req,function(){
					if(req.headers["content-type"]==="application/x-www-form-urlencoded"){
						// a=1&b=2&c=3 ===>[a=1,b=2,c=3]
						const obj = {};
						req.body.split("&").forEach(item=>{
							const [key,value] = item.split("=")
							obj[key] = value;
						})
						req.body = obj;
					}
					next();
				});
			}else{
				next();
			}
		}
	}
}